package org.feng.datasource.config;

import lombok.Setter;
import org.feng.datasource.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 数据源属性配置
 *
 * @version v1.0
 * @author: fengjinsong
 * @date: 2022年05月06日 13时01分
 */
@RefreshScope
@ConfigurationProperties(prefix = DataSourcePropertiesConfig.PREFIX)
public class DataSourcePropertiesConfig {
    /**
     * 前缀
     */
    public static final String PREFIX = "spring.datasource";

    private static final String DRIVER_CLASS_PREFIX = "driverClassName=";
    private static final String JDBC_URL_PREFIX = "jdbcUrl=";
    private static final String USERNAME_PREFIX = "username=";
    private static final String PASSWORD_PREFIX = "password=";

    /**
     * key=租户，value=连接数据库的参数
     */
    @Setter
    private Map<String, Set<String>> config;

    public Map<String, DataSourceProperties> getDataSourceConfig() {
        Map<String, DataSourceProperties> resultMap = new HashMap<>(16);
        config.forEach((merchant, setConfig) -> {
            DataSourceProperties properties = setToProperties(setConfig);
            resultMap.put(merchant, properties);
        });
        return resultMap;
    }

    private static DataSourceProperties setToProperties(Set<String> setConfig) {
        DataSourceProperties dataSourceProperties = new DataSourceProperties();
        for (String param : setConfig) {
            if (param.startsWith(DRIVER_CLASS_PREFIX)) {
                dataSourceProperties.setDriverClassName(param.replaceFirst(DRIVER_CLASS_PREFIX, ""));
                continue;
            }
            if (param.startsWith(JDBC_URL_PREFIX)) {
                dataSourceProperties.setJdbcUrl(param.replaceFirst(JDBC_URL_PREFIX, ""));
                continue;
            }
            if (param.startsWith(USERNAME_PREFIX)) {
                dataSourceProperties.setUsername(param.replaceFirst(USERNAME_PREFIX, ""));
                continue;
            }
            if (param.startsWith(PASSWORD_PREFIX)) {
                dataSourceProperties.setPassword(param.replaceFirst(PASSWORD_PREFIX, ""));
            }
        }
        return dataSourceProperties;
    }
}
